<template>
  <div class="add-container">
    <el-row :gutter="24" class="mb8">
      <el-col :span="8"> {{ operationTitle }}图文</el-col>
      <el-col :span="16" style="text-align: right;">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="$router.go(0)">
          刷新
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="$router.go(-1)"
          >返回
        </el-button>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button
          type="primary"
          size="mini"
          style="float: right;"
          @click="$router.push({ path: '/gwoper/label' })"
          >标签管理
        </el-button>
      </div>
      <div class="text item">
        <el-form
          ref="addForm"
          :model="formData"
          :rules="this.formData.onSell == 1?rules:rulesAdd"
          size="medium"
          :label-position="isSmall ? 'top' : 'right'"
          label-width="130px"
        >
          <el-row :gutter="24">
            <el-col :span="8" :lg="8" :md="10" :sm="12" :xs="24" class="col_1">
              <el-form-item label="资讯图文标题：" prop="title">
                <el-input
                  v-model="formData.title"
                  placeholder="请输入资讯图文标题"
                  show-word-limit
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
              <el-form-item label="资讯图文标签：" prop="labelId">
                <el-select
                  v-model="formData.labelId"
                  placeholder="请选择资讯图文标签"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in labelList"
                    :key="index"
                    :label="item.labelName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="正文内容：" prop="contentType">
                <el-select
                  v-model="formData.contentType"
                  placeholder="请选择正文内容"
                  clearable
                  :style="{ width: '100%' }"
                  @change="changeConType"
                >
                  <el-option
                    v-for="(item, index) in contentOptions"
                    :key="index"
                    :label="item.dictLabel"
                    :value="Number(item.dictValue)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="URL地址："
                prop="content"
                v-if="formData.contentType==0"
              >
                <el-input
                  v-model="formData.content"
                  placeholder="请输入URL地址"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
              <el-form-item label="开始时间：" prop="showBeginTime">
                <el-date-picker
                  v-model="formData.showBeginTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择开始时间"
                  :picker-options="startDatePicker"
                  @change="changeStartValue"
                  clearable
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间：" prop="showEndTime">
                <el-date-picker
                  v-model="formData.showEndTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择结束时间"
                  :picker-options="endDatePicker"
                  @change="changeEndValue"
                  clearable
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="排序值：" prop="orderNo" v-if="this.formData.onSell == 1">
                <el-input
                  v-model="formData.orderNo"
                  placeholder="请输入排序值"
                  clearable
                  :style="{ width: '100%' }"
                  @input="inputValue"
                ></el-input>
              </el-form-item>
              <el-form-item label="展示图片：" prop="cover">
                <el-image :src="formData.cover" alt="" v-loading="isUploading" element-loading-text="图片上传中...">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div>
                  请上传XXX*XXXX像素jpg/jpeg/png格式的图片，展示效果最佳，文件大小不超过XXXXX
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-upload
                      ref="imgUrl"
                      name="multipartFile"
                      :file-list="imgUrlFileList"
                      :action="imgUrlAction"
                      :headers="headers"
                      :disabled="isUploading"
                      :limit="1"
                      accept=".jpg,.jpeg,.png"
                      :on-exceed="handleExceed"
                      :on-success="handleAvatarSuccess"
                      :before-upload="imgUrlBeforeUpload"
                      :on-progress="handleUploadProgress"
                    >
                      <el-button size="small" type="primary"
                        >本地上传
                      </el-button>
                    </el-upload>
                  </el-col>
                  <el-col :span="12" style="text-align:right;">
                    <el-button
                      size="small"
                      type="primary"
                      @click="deleteNewsImg"
                      >删除</el-button
                    >
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="16" :lg="16" :md="14" :sm="12" :xs="24" class="col_2">
              <el-form-item label="摘要：" prop="summary">
                <el-input
                  v-model="formData.summary"
                  type="textarea"
                  placeholder="请输入摘要"
                  :autosize="{ minRows: 1, maxRows: 37 }"
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
              <el-form-item prop="content">
                <!-- <wang-editor :editValue="editValue" :isEdit="isEdit" @changeEditor="changeEditor"></wang-editor>-->
                <tinymce-editor
                  ref="tinymceEd"
                  :editValue="editValue"
                  :isEdit="isEdit"
                  @changeEditor="changeEditor"
                ></tinymce-editor>
              </el-form-item>
              <el-form-item size="large">
                <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="previewNews">预览</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import {
  getInformation,
  addInformation,
  updateInformation,
  deleteNewsImg
} from "@/api/gwoper/news";
import { listLabel } from "@/api/gwoper/label";
import WangEditor from "@/components/News/wangeditor";
import TinymceEditor from "@/components/News/tiny";

export default {
  name: "AddNews",
  components: { TinymceEditor, WangEditor },
  data() {
    let validateContent = (rule, value, callback) => {
      console.log(rule)
      const reg = /(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)/
      if(this.formData.contentType==0){
        if(!value){
          callback(new Error('请输入内容'));
        }else if (!reg.test(value)) {
          callback(new Error('请输入正确的URL格式（http、https、ftp、ftps）'));
        } else {
          callback();
        }
      }else{
        if (!value) {
          callback(new Error('请输入内容'));
        } else {
          callback();
        }
      }
    };
    return {
      isUploading: false,// 图片上传蒙层
      loading: false,
      labelList: [], // 图文标签列表
      contentOptions: [],
      formData: {
        id: null,
        title: "",
        labelId: "",
        contentType: null,
        content: null,
        showBeginTime: null,
        showEndTime: null,
        orderNo: null,
        cover: null,
        summary: null,
        onSell: 2, // 上下架（0-下架  1-上架 2-待上架）
        publishTime: null // 发布时间
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入资讯图文标题",
            trigger: "blur"
          }
        ],
        labelId: [
          {
            required: true,
            message: "请选择资讯图文标签",
            trigger: "change"
          }
        ],
        contentType: [
          {
            required: true,
            message: "请选择正文内容",
            trigger: "change"
          }
        ],
        content: [
          {
            required: true,
            validator: validateContent,
            trigger: 'blur'
          }
        ],
        showBeginTime: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: "change"
          }
        ],
        showEndTime: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: "change"
          }
        ],
        orderNo: [
          {
            required: true,
            message: "请输入排序值",
            trigger: "blur"
          }
        ],
        cover: [
          {
            required: true,
            message: "请插入展示图片",
            trigger: "blur"
          }
        ],
        summary: [
          {
            required: true,
            message: "请输入摘要",
            trigger: "blur"
          },
          { max:200, message:"摘要长度不能超过200个字符串", trigger: "blur" }
        ]
      },
      rulesAdd: {
        title: [
          {
            required: true,
            message: "请输入资讯图文标题",
            trigger: "blur"
          }
        ],
        labelId: [
          {
            required: true,
            message: "请选择资讯图文标签",
            trigger: "change"
          }
        ],
        summary: [
          { max:200, message:"摘要长度不能超过200个字符串", trigger: "blur" }
        ]
      },
      // 时间选择
      startDatePicker: this.processDateStart(),
      endDatePicker: this.processDateEnd(),
      isSmall: false, // 屏幕大小变化改变样式状态
      screenWidth: document.body.clientWidth, // 屏幕宽度
      imgUrlAction:
        process.env.VUE_APP_BASE_API + "/operation-center/banner/upload", // 上传接口
      imgUrlFileList: [],
      headers: {
        Authorization: "Bearer " + getToken()
      },
      editValue: "",
      content: null,
      editorOption: {},
      operationTitle: "",
      isEdit: false // true-富文本；false-URL
    };
  },
  mounted() {
    const that = this;
    window.addEventListener("resize", function() {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
    });
    if (that._isMobile()) {
      // 手机端
      this.isSmall = true;
    } else {
      // pc端
      this.isSmall = false;
    }
  },
  watch: {
    screenWidth(val) {
      console.log(val)
      this.screenWidth = val;
      if (this.screenWidth < 768) {
        this.isSmall = true;
      } else {
        this.isSmall = false;
      }
    },
  },
  created() {
    this.formData.id = this.$route.query.id ? this.$route.query.id : null;
    this.getDicts("gwoper_news_content").then(response => {
      this.contentOptions = response.data;
    });
    this.getList()
    if (this.formData.id) {
      this.getInfo();
      this.operationTitle = "修改";
    } else {
      this.operationTitle = "新增";
    }

  },
  methods: {
    _isMobile() {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
      return flag;
    },
    inputValue(value){
      if(value.length > 1 && value.slice(0,1)==0){
        return this.formData.orderNo = 0;
      }
      this.formData.orderNo = value.replace(/[^\d]/g,'');
    },
    changeStartValue(value){
      if(this.formData.showEndTime){
        if((new Date(value).getTime())>=new Date(this.formData.showEndTime).getTime()){
          this.formData.showBeginTime = null
          this.msgInfo('开始时间需小于结束时间');
        }
      }
    },
    changeEndValue(value){
      console.log(new Date(value).getTime())
      if(new Date(value).getTime()<=new Date(this.formData.showBeginTime).getTime()){
        this.formData.showEndTime = null
        this.msgInfo('结束时间需大于开始时间');
      }
    },
    // 开始时间不能大于结束时间
    processDateStart() {
      const that = this;
      return {
        disabledDate(time) {
          // 如果结束时间不为空，则开始时间小于结束时间
          if (that.formData.showEndTime) {
            return (
              new Date(that.formData.showEndTime).getTime() < time.getTime()
            );
          }
        },
      };
    },
    /* 结束时间不能小于开始时间 */
    processDateEnd() {
      const that = this;
      return {
        disabledDate(time) {
          // 如果开始时间不为空，则结束时间大于开始时间
          if (that.formData.showBeginTime) {
            return (
              new Date(that.formData.showBeginTime).getTime() > time.getTime()
            );
          }
        },
      };
    },
    // 子组件值改变，父组件值相应改变(子组件触发)
    changeEditor(val) {
      this.editValue = val;
    },
    // 预览资讯图文
    previewNews() {
      const id = this.formData.id;
      if (this.formData.id) {
        this.$router.push({
          path: "/gwoper/preview",
          query: { id: id }
        });
      }
    },
    // 改变正文内容select选项
    changeConType(val) {
      this.formData.content = "";
      if (val == 0) {
        this.isEdit = false;
      } else if (val == 1) {
        this.isEdit = true;
      }
    },
    handleExceed(files, fileList) {
      console.log(files, fileList);
      this.$refs["imgUrl"].clearFiles();
      this.imgUrlBeforeUpload(files);
    },
    // 图片上传成功时的钩子
    handleAvatarSuccess(res, file) {
      console.log(res, file);
      this.formData.cover = file.response;
      this.imgUrlFileList[0] = {
        name: file.name,
        url: file.response
      };
      this.$refs.imgUrl.clearFiles();
      this.isUploading = false
    },
    // 图片文件之前的钩子
    imgUrlBeforeUpload(file) {
      console.log(file);
    },
    // 文件上传中处理
    handleUploadProgress(event, file, fileList) {
      this.isUploading = true;
    },
    // 删除banner
    deleteNewsImg() {
      let id = this.formData.id;
      if (id) {
        deleteNewsImg(id)
          .then(res => {
            console.log(res);
            if (res.code != 200) {
              return this.msgError(res.msg);
            }
            this.msgSuccess(res.msg);
            this.formData.cover = "";
            this.imgUrlFileList = [];
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.formData.cover = "";
        this.imgUrlFileList = [];
      }
    },
    // 获取图文详情
    getInfo() {
      getInformation(this.formData.id)
        .then(response => {
          console.log(response);
          if (response.code != 200) {
            return this.msgError(response.msg);
          }
          this.formData = response.data;
          if (this.formData.contentType == 1) {
            this.editValue = this.formData.content;
            console.log(this.formData.content);
            this.isEdit = true;
          } else {
            this.isEdit = false;
          }
          console.log(this.isEdit);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 获取图文标签列表
    getList() {
      listLabel({ status: 1, pageNum: 1, pageSize: 10000 })
        .then(response => {
          console.log(response);
          if (response.code != 200) {
            return this.msgError(response.msg);
          }
          this.labelList = response.rows;
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 保存提交
    submitForm() {
      this.loading = true
      if (this.formData.contentType == 1) {
        this.formData.content = this.editValue;
      }
      if (this.formData.id == null) {
        this.$refs["addForm"].validate(valid => {
          console.log(valid)
          if(!valid) return this.loading = false
          addInformation(this.formData).then(response => {
            console.log(response);
            if (response.code != 200) {
              this.loading = false
              return this.msgError(response.msg);
            }
            this.msgSuccess(response.msg);
            this.resetForm();
            this.loading = false
            this.$router.push({path: "/gwoper/news"});
          }).catch(error=>{
            console.log(error)
            this.loading = false
          });
        })
      } else {
        if (this.formData.onSell == 0) {
          this.formData.onSell = 2;
        }
        this.$refs["addForm"].validate(valid => {
          if (!valid) return this.loading = false
          updateInformation(this.formData).then(response => {
            console.log(response);
            if (response.code != 200) {
              this.loading = false
              return this.msgError(response.msg);
            }
            this.msgSuccess(response.msg);
            this.resetForm();
            this.loading = false
            this.$router.push({ path: "/gwoper/news" });
          }).catch(error=>{
            console.log(error)
            this.loading = false
          });;
        });
      }
    },
    // 重置表单
    resetForm() {
      this.editValue = "";
      this.$refs["addForm"].resetFields();
      console.log(this.formData)
    }
  }
};
</script>
<style lang="scss">
@import "@/assets/styles/card.scss";

.add-container {
  padding: 20px;

  .el-textarea__inner {
    min-height: 200px !important;
  }

  .el-form-item__label {
    width: 130px !important;
  }

  .el-col-16 {
    .el-form-item__label {
      width: 80px !important;
    }
  }

  .el-col-16:last-child {
    .el-form-item {
      .el-form-item__content {
        margin-left: 20px !important;
      }
    }

    .el-form-item:last-child {
      .el-form-item__content {
        margin-left: 0 !important;
        text-align: center;
      }
    }
  }

  .el-col-xs-24:last-child {
    .el-form-item {
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }

  .el-form-item--large {
    text-align: right;
  }

  .el-image {
    position: relative;
    width: 100%;
    min-height: 150px;
    border: 1px solid #dcdfe6;

    .image-slot {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);

      .el-icon-picture-outline:before {
        font-size: 50px;
        color: #dcdfe6;
      }
    }
  }
}

.el-upload__tip {
  line-height: 1.2;
}
</style>
